package com.palrevo.data.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.palrevo.data.dao.DAO;
import com.palrevo.data.dao.DAOFactory;
import com.palrevo.data.dao.DaoRecord;
import com.palrevo.data.dao.DataException;
import com.palrevo.data.models.User;

/**
 * 
 * @author AAsha
 *
 */
public class AuthenticationDBService extends ServiceBase{
	
	/**
	 * 
	 */
	private AuthenticationDBService(){
	}
	
	/**
	 * 
	 * @author AAsha
	 *
	 */
	private static class SingletonHolder{
		private static AuthenticationDBService instance = new AuthenticationDBService(); 
	}
	
	/**
	 * 
	 * @return AuthenticationDBService instance
	 */
	public static AuthenticationDBService getInstance(){
		return SingletonHolder.instance;
	}
	
	/**
	 * 
	 * @param username
	 * @return User by its username
	 * @throws DataException
	 */
	public User loadUser(String username) throws DataException{
		
		DAO dao = DAOFactory.getInstance().createDao();
		
		String sql = "SELECT * FROM "+ Tables.users.name() +" WHERE "+ Columns.USERNAME.name() + " = '"+ username +"'";
		dao.execute(sql);
		
		User user = null;
		
		for(DaoRecord record:dao.getResult()){
			
			user = new User();
			user.setId((Long) record.getValue(Columns.ID.name()));
			user.setUsername((String) record.getValue(Columns.USERNAME.name()));
			user.setPassword((String) record.getValue(Columns.PASSWORD.name()));
		}
		
		
		return user;
	}
	
	
	public void changePassword(User user) throws DataException{
		
		DAO dao = DAOFactory.getInstance().createDao();
		
		Map<Integer, Object> params = new HashMap<Integer, Object>();
		params.put(1, user.getUsername());
		params.put(2, user.getPassword());
		params.put(3, user.getId());
		
		List<String> keys = new ArrayList<String>();
		keys.add(Columns.ID.name());
		
		dao.update(user, keys, params);
		
	}
}
